package com.wits.platform.dao.impl;

import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;

import com.wits.platform.dao.custom.UserDaoCustom;
import com.wits.platform.entity.User;
import com.wits.platform.web.mvc.PageParam;

@Component
public class UserDaoImpl extends BaseDaoImpl<User,String> implements UserDaoCustom{

	private static String SQL_FIND_USER_BY_ROLE="select u.* from wits_user u inner join wits_mmr_user_role ur on(u.user_id=ur.user_id)  where u.is_enable='T' and ur.role_id=?";
	
	
	
	
	
	
	@Override
	public Page<User> findUserPageByRole(Map<String, Object> filterParams,PageParam pageParam,String roleId) {
		return this.findPageByNative(User.class,SQL_FIND_USER_BY_ROLE, pageParam,roleId);
	}
	
	@Override
	public List<User> findUserByRole(Map<String, Object> filterParams,String roleId) {
		return this.findByNative(User.class,SQL_FIND_USER_BY_ROLE,roleId);
	}
	

	@Override
	public Page<User> findUserNoRole(Map<String, Object> filterParams,PageParam pageParam, String roleId,String excludeUserId) {
		String sql="select u.* from wits_user u left join wits_mmr_user_role ur on(u.user_id=ur.user_id)  where u.is_enable='T'";
		if(StringUtils.isNotEmpty(roleId)){
			sql+=" and ur.role_id!='"+roleId+"'";
		}
		if(StringUtils.isNotEmpty(excludeUserId)){
			sql+=" and u.user_id not in("+excludeUserId+")";
		}
		return this.findPageByNative(User.class, sql, pageParam);
	}

	@Override
	public void deleteInBatch(String ids) {
		String sql="delete from wits_user where user_id in(%s)";
		this.executeUpdateByNative(String.format(sql, ids));
		
	}

	@Override
	public boolean isExist(User user) {
		String hql="from User o where o.userId ='"+user.getUserId()+"'";
		List<User> list = this.find(User.class, hql, null);
		if(list!=null && list.size()>0) 
			return true;
		return false;
	}
	
	public List<User> findAllTeacherAndStudent() {
		Query query = em.createQuery( "FROM User o WHERE o.usertype in ('stu', 'tea')" );
		return query.getResultList();
	}
	
}
